package com.kaizeli.website.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaizeli.website.exception.BusinessErrorEnum;
import com.kaizeli.website.exception.BusinessException;
import com.kaizeli.website.mapper.EmployeeMapper;
import com.kaizeli.website.pojo.dto.base.PageDTO;
import com.kaizeli.website.pojo.model.EmployeeDO;
import com.kaizeli.website.pojo.model.EmployeeSimpleDO;
import com.kaizeli.website.pojo.vo.EmployeeVO;
import com.kaizeli.website.query.EmployeeQuery;
import com.kaizeli.website.service.EmployeeService;
import com.kaizeli.website.util.AsserterUtil;
import com.kaizeli.website.util.DateTimeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工服务实现类（简化版）
 */
@Service("employeeSimpleService")
@RequiredArgsConstructor
public class EmployeeSimpleServiceImpl implements EmployeeService {
    
    private final EmployeeMapper employeeMapper;
    
    @Override
    public PageDTO<EmployeeVO> pageQuery(EmployeeQuery query) {
        // 构建查询条件
        LambdaQueryWrapper<EmployeeDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getEmployeeCode()), EmployeeDO::getEmployeeCode, query.getEmployeeCode())
                .like(StrUtil.isNotBlank(query.getName()), EmployeeDO::getName, query.getName())
                .eq(StrUtil.isNotBlank(query.getGender()), EmployeeDO::getGender, query.getGender())
                .like(StrUtil.isNotBlank(query.getPhone()), EmployeeDO::getPhone, query.getPhone())
                .like(StrUtil.isNotBlank(query.getEmail()), EmployeeDO::getEmail, query.getEmail())
                .like(StrUtil.isNotBlank(query.getDepartment()), EmployeeDO::getDepartment, query.getDepartment())
                .like(StrUtil.isNotBlank(query.getPosition()), EmployeeDO::getPosition, query.getPosition())
                .eq(query.getStatus() != null, EmployeeDO::getStatus, query.getStatus())
                // 只查询未删除的员工（状态不为0）
                .ne(EmployeeDO::getStatus, 0)
                .orderByDesc(EmployeeDO::getCreateTime);
        
        // 分页查询
        Page<EmployeeDO> page = employeeMapper.selectPage(query.toMpPage(), wrapper);
        
        // 转换为VO
        return PageDTO.of(page, this::convertToVO);
    }
    
    @Override
    public EmployeeVO getById(Long id) {
        AsserterUtil.notNull(id, BusinessErrorEnum.EMPLOYEE_ID_NOT_NULL);
        
        EmployeeDO employeeDO = employeeMapper.selectById(id);
        if (employeeDO == null) {
            throw new BusinessException(BusinessErrorEnum.EMPLOYEE_NOT_FOUND);
        }
        
        return convertToVO(employeeDO);
    }
    
    @Override
    public EmployeeVO getByEmployeeCode(String employeeCode) {
        AsserterUtil.notNull(employeeCode, BusinessErrorEnum.EMPLOYEE_CODE_NOT_NULL);
        
        EmployeeDO employeeDO = employeeMapper.selectByEmployeeCode(employeeCode);
        if (employeeDO == null) {
            throw new BusinessException(BusinessErrorEnum.EMPLOYEE_NOT_FOUND);
        }
        
        return convertToVO(employeeDO);
    }
    
    @Override
    public Long save(EmployeeDO employeeDO) {
        AsserterUtil.notNull(employeeDO, BusinessErrorEnum.EMPLOYEE_INFO_NOT_NULL);
        
        // 验证必填字段
        AsserterUtil.notNull(employeeDO.getName(), BusinessErrorEnum.EMPLOYEE_NAME_NOT_NULL);
        AsserterUtil.notNull(employeeDO.getPhone(), BusinessErrorEnum.EMPLOYEE_PHONE_NOT_NULL);
        AsserterUtil.notNull(employeeDO.getEmail(), BusinessErrorEnum.EMPLOYEE_EMAIL_NOT_NULL);
        
        // 检查员工编号是否已存在（如果提供了员工编号）
        if (StrUtil.isNotBlank(employeeDO.getEmployeeCode())) {
            EmployeeDO existEmployee = employeeMapper.selectByEmployeeCode(employeeDO.getEmployeeCode());
            if (existEmployee != null) {
                throw new BusinessException(BusinessErrorEnum.EMPLOYEE_CODE_DUPLICATE);
            }
        }
        
        // 设置默认状态为在职
        if (employeeDO.getStatus() == null) {
            employeeDO.setStatus(1);
        }
        
        // 手动设置时间戳（因为暂时禁用了自动填充插件）
        LocalDateTime currentTime = LocalDateTime.now();
        employeeDO.setCreateTime(currentTime);
        employeeDO.setUpdateTime(currentTime);
        
        employeeMapper.insert(employeeDO);
        return employeeDO.getId();
    }
    
    @Override
    public Boolean update(EmployeeDO employeeDO) {
        AsserterUtil.notNull(employeeDO, BusinessErrorEnum.EMPLOYEE_INFO_NOT_NULL);
        AsserterUtil.notNull(employeeDO.getId(), BusinessErrorEnum.EMPLOYEE_ID_NOT_NULL);
        
        // 检查员工是否存在
        EmployeeDO existEmployee = employeeMapper.selectById(employeeDO.getId());
        if (existEmployee == null) {
            throw new BusinessException(BusinessErrorEnum.EMPLOYEE_NOT_FOUND);
        }
        
        // 如果更新员工编号，检查是否重复
        if (StrUtil.isNotBlank(employeeDO.getEmployeeCode()) && 
            !employeeDO.getEmployeeCode().equals(existEmployee.getEmployeeCode())) {
            EmployeeDO duplicateEmployee = employeeMapper.selectByEmployeeCode(employeeDO.getEmployeeCode());
            if (duplicateEmployee != null) {
                throw new BusinessException(BusinessErrorEnum.EMPLOYEE_CODE_DUPLICATE);
            }
        }
        
        int result = employeeMapper.updateById(employeeDO);
        return result > 0;
    }
    
    @Override
    public Boolean deleteById(Long id) {
        AsserterUtil.notNull(id, BusinessErrorEnum.EMPLOYEE_ID_NOT_NULL);
        
        // 检查员工是否存在
        EmployeeDO existEmployee = employeeMapper.selectById(id);
        if (existEmployee == null) {
            throw new BusinessException(BusinessErrorEnum.EMPLOYEE_NOT_FOUND);
        }
        
        // 软删除：将状态设为0（删除状态）
        EmployeeDO updateEmployee = new EmployeeDO();
        updateEmployee.setId(id);
        updateEmployee.setStatus(0); // 设置为离职/删除状态
        
        int result = employeeMapper.updateById(updateEmployee);
        return result > 0;
    }
    
    @Override
    public Boolean deleteBatchByIds(List<Long> ids) {
        AsserterUtil.notNull(ids, BusinessErrorEnum.EMPLOYEE_ID_NOT_NULL);
        AsserterUtil.isTrue(!ids.isEmpty(), BusinessErrorEnum.EMPLOYEE_ID_NOT_NULL);
        
        // 软删除：批量将状态设为0（删除状态）
        for (Long id : ids) {
            EmployeeDO updateEmployee = new EmployeeDO();
            updateEmployee.setId(id);
            updateEmployee.setStatus(0); // 设置为离职/删除状态
            employeeMapper.updateById(updateEmployee);
        }
        
        return true;
    }
    
    @Override
    public Boolean updateStatus(Long id, Integer status) {
        AsserterUtil.notNull(id, BusinessErrorEnum.EMPLOYEE_ID_NOT_NULL);
        AsserterUtil.notNull(status, BusinessErrorEnum.EMPLOYEE_STATUS_INVALID);
        AsserterUtil.isTrue(status == 0 || status == 1, BusinessErrorEnum.EMPLOYEE_STATUS_INVALID);
        
        // 检查员工是否存在
        EmployeeDO existEmployee = employeeMapper.selectById(id);
        if (existEmployee == null) {
            throw new BusinessException(BusinessErrorEnum.EMPLOYEE_NOT_FOUND);
        }
        
        EmployeeDO updateEmployee = new EmployeeDO();
        updateEmployee.setId(id);
        updateEmployee.setStatus(status);
        
        int result = employeeMapper.updateById(updateEmployee);
        return result > 0;
    }
    
    @Override
    public List<EmployeeVO> getEmployeesByStatus(Integer status) {
        AsserterUtil.notNull(status, BusinessErrorEnum.EMPLOYEE_STATUS_INVALID);
        AsserterUtil.isTrue(status == 0 || status == 1, BusinessErrorEnum.EMPLOYEE_STATUS_INVALID);
        
        // 使用自定义SQL查询，避免时间戳转换问题
        List<EmployeeDO> employeeList = employeeMapper.selectEmployeesByStatus(status);
        
        // 转换为VO
        return employeeList.stream()
                .map(this::convertToVO)
                .collect(java.util.stream.Collectors.toList());
    }
    
    /**
     * 将EmployeeDO转换为EmployeeVO
     */
    private EmployeeVO convertToVO(EmployeeDO employeeDO) {
        EmployeeVO vo = BeanUtil.copyProperties(employeeDO, EmployeeVO.class);
        
        // 转换状态描述
        if (employeeDO.getStatus() != null) {
            vo.setStatusDesc(employeeDO.getStatus() == 1 ? "在职" : "离职");
        }
        
        // 转换时间格式 - 直接格式化LocalDateTime
        if (employeeDO.getCreateTime() != null) {
            vo.setCreateTime(employeeDO.getCreateTime().toString().replace("T", " "));
        }
        if (employeeDO.getUpdateTime() != null) {
            vo.setUpdateTime(employeeDO.getUpdateTime().toString().replace("T", " "));
        }
        
        return vo;
    }
    
    @Override
    public List<EmployeeVO> search(String keyword) {
        QueryWrapper<EmployeeDO> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(keyword), "name", keyword)
                .or()
                .like(StrUtil.isNotBlank(keyword), "employee_code", keyword)
                .orderByDesc("create_time");
        
        List<EmployeeDO> list = employeeMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    @Override
    public List<EmployeeVO> getAllEmployees() {
        List<EmployeeDO> list = employeeMapper.selectList(null);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }
}
